const express = require('express');
const path = require('path');
const config = require('config');
const useragent = require('express-useragent');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const url = require('url');
var fs = require('fs');
const paramUtil = require('./utils/paramUtil');
const sessionUtil = require('./utils/sessionUtil');

const app = express();
app.disable('x-powered-by');
app.use(useragent.express());

app.set('views', path.join(__dirname, 'views'));
app.engine('.html', require('ejs').__express);
app.set('view engine', 'ejs');

// 解决post的请求量太大，被express限制的问题
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

const logger = require('./utils/logger');
// logger.use(app)

app.use(cookieParser(config.get('session.secret')));
// const redis = require('redis');
// const expressSession = require('express-session');
// const RedisStrore = require('connect-redis')(expressSession);
// let redisConfig = config.get('redis');
// redisConfig.logErrors = err => {
//   let errorMessage = err.message || err.toString();
//   logger.echo('Redis', errorMessage + ' ' + err.stack);
// };
// app.use(
//   expressSession({
//     secret: config.get('session.secret'),
//     name: config.get('session.name'),
//     resave: false,
//     rolling: true,
//     saveUninitialized: false,
//     cookie: config.get('session.cookie'),
//     store: new RedisStrore({ client: redis.createClient(redisConfig) }),
//   })
// );

//登录鉴权初始化
const passportUtil = require('./utils/passportUtil');
passportUtil.init(app);
app.use(passportUtil.authenticateMiddleWare);

const multer = require('multer');
let storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.join(__dirname, '../upload'));
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname);
  },
});
let upload = multer({ storage });
let cpUpload = upload.any();
app.use(cpUpload);

app.use((req, res, next) => {
  if (process.env.NODE_ENV === 'development') {
    res.header('Access-Control-Allow-Origin', '*');
  }

  let method = req.method.toLowerCase();
  if (['get', 'post', 'option'].indexOf(method) < 0) {
    return res.sendStatus(404);
  }

  let params = paramUtil.getParams(req, false);
  for (let key in params) {
    let value = params[key];
    if (/<[^>]+>/.test(value)) {
      res.status(400);
      res.json({
        code: -1,
        msg: `dangerous! key:${key} ,value:${value}`,
      });
      return;
    }
  }
  next();
});

//初始化平台接口SDK
// const serverSDK = require('server-sdk');
const productSecret = config.get('productSecret');
const apiServerConfig = config.get('apiServer');
const bigDataInfo = config.get('bigDataInfo');
// serverSDK.init({
//   bigDataInfo,
//   apiServer: { ...apiServerConfig },
//   getWay: {
//     productKey: '7fa88133-e2c',
//     platform: 'aliyun',
//   },
//   signSecretGetter: productKey => Promise.resolve(productSecret[productKey]),
//   logger,
//   regionHttps: config.get('regionHttps'),
// });

require('./routes')(app);

app.use(require('./utils/rewritePage'));

if (process.env.NODE_ENV === 'development') {
  const webpack = require('webpack');
  const webpackConfig = require('../client/build/webpack.config.dev');
  const devMiddleware = require('webpack-dev-middleware');
  const hotMiddleware = require('webpack-hot-middleware');
  const compiler = webpack(webpackConfig);
  app.use(
    devMiddleware(compiler, {
      publicPath: webpackConfig.output.publicPath,
      writeToDisk: filePath => /\.html$/.test(filePath),
    })
  );
  app.use(hotMiddleware(compiler));
}

app.use((req, res, next) => {
  if (req.rewriteUrl) {
    let root = path.join(__dirname, '../client/dist');
    let filePath = path.join(root, req.rewriteUrl);

    let pageParams = {};
    if (req.rewriteUrl !== 'login.html') {
      let userInfo = sessionUtil.getUserInfo(req);
      delete userInfo.user_pwd;
      pageParams = {
        userInfo,
        h5player: config.get('h5player'),
        webSocketServer: config.get('webSocketServer'),
        env: config.get('env'),
      };
    }

    fs.access(filePath, function (err) {
      if (err) next();
      else {
        res.render(filePath, { pageParams: JSON.stringify(pageParams) });
      }
    });
  } else {
    next();
  }
});

app.use(express.static(path.join(__dirname, '../client/dist')));
app.use('/static', express.static(path.join(__dirname, '../client/static')));

app.use(function (req, res, next) {
  res.sendStatus(404);
});

app.use(function (err, req, res, next) {
  let errorMessage = '';
  try {
    errorMessage = JSON.stringify(err);
  } catch (e) {
    errorMessage = err.message || err.toString();
  }
  let params = paramUtil.getParams(req);
  logger.print(req.path, params, errorMessage, 0, 'ERROR', req.method);

  let status = err.status || 500;
  res.status(status || 500);
  res.render('error');
});

module.exports = app;
